import { Injectable } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { Like, Repository } from 'typeorm'
import { Career } from '@/modules/career/entities/career.entity'
import {
  CreateCareerDto,
  FindCareerDto,
  ListPageCareerDto,
  ListPaginationCareerVo,
  UpdateCareerDto,
} from './dto/career.dto'

@Injectable()
export class CareerService {
  constructor(
    @InjectRepository(Career)
    private careerRepository: Repository<Career>,
  ) {}

  create(data: CreateCareerDto) {
    return this.careerRepository.save(data)
  }

  async findOne(data: FindCareerDto) {
    return await this.careerRepository.findOneBy(data)
  }

  async findPage(query: ListPageCareerDto): Promise<ListPaginationCareerVo> {
    const { pageNo = 1, pageSize = 10, ...rest } = query
    const [list, total] = await this.careerRepository.findAndCount({
      where: {
        ...rest,
        // 不这样做，不传值的时候会当做 undefined 来查找，导致返回空列表
        ...(rest.careerName && { careerName: Like(`%${rest.careerName}%`) }),
      },
      skip: (pageNo - 1) * pageSize,
      take: pageSize,
      order: {
        createdAt: 'DESC',
      },
    })

    return {
      total,
      list,
    }
  }

  async update(careerId: number, updateData: UpdateCareerDto) {
    return this.careerRepository.update(careerId, {
      ...updateData,
      careerId: undefined,
    })
  }

  remove(careerId: number) {
    return this.careerRepository.delete(careerId)
  }
}
